<template>
  <div class="main">
    <el-card>
      <div class="upload-test-group">
        <el-divider content-position="left">第二步 测试集上传</el-divider>
        <el-form ref="uploadForm">
          <el-form-item label="类型选择">
            <el-select v-model="type" placeholder="请选择类型">
              <el-option label="JSON" value="1"></el-option>
              <el-option label="URL" value="2"></el-option>
              <el-option label="文件上传" value="3"></el-option>
            </el-select>
          </el-form-item>

          <!-- Conditionally render input fields based on the selected type -->
          <el-form-item v-if="type === '1'" label="内容">
            <el-input
                type="textarea"
                v-model="content"
                :rows="36"
                placeholder="请输入测试集Json格式内容"
            ></el-input>
          </el-form-item>

          <el-form-item v-if="type === '2'" label="内容">
            <el-input v-model="content" placeholder="请输入测试集所在的URL"></el-input>
          </el-form-item>

          <el-form-item v-if="type === '3'" label="上传文件">
            <el-upload
                class="upload-demo"
                drag
                ref="uploadRef"
                :headers="{'Problem-Id': problemId}"
                :before-upload="beforeUpload"
                :auto-upload="false"
                :on-change="handleFileChange"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip">只支持单个.json文件</div>
            </el-upload>
          </el-form-item>

          <el-button size="large" class="next2" type="primary" @click="submitData">下一步</el-button>
        </el-form>
      </div>
    </el-card>
  </div>
</template>


<script setup>
import {ref, onMounted, computed, watch} from 'vue';
import {ElMessage} from 'element-plus';
import axios from "axios";
import {API_BASE_URL, AUTH_TOKEN} from '@/config.ts';
import router from "@/router";
import {useStore} from "vuex";
import {useRoute} from "vue-router";

const store = useStore();
const problemId = ref(null);


const type = ref('3');
const content = ref('');
const fileList = ref([]);
let pId = null;
const route = useRoute();
let editing = null;

onMounted(async () => {
  console.log(route.query.editing)
  console.log(route.query.id)
  console.log(route.query)
  if (route.query.editing==='1') {
    pId = route.query.id;
    editing = route.query.editing;
    if (pId) {
      try {
        const url = `${API_BASE_URL}/ProblemsGroup/problems/testGroup/${pId}`;
        const response = await axios.get(url, {
          headers: {
            'token': AUTH_TOKEN
          }
        });

        if (response.data.code === 200) {
          const jsonData = response.data.data;
          // Assuming jsonData.content is a JSON string with escaped characters
          const unescapedContent = JSON.parse(jsonData.content);
          content.value = JSON.stringify(unescapedContent, null, 2);
          type.value = '1';
          problemId.value = pId;
        } else {
          ElMessage.error('获取题目内容失败');
        }
      } catch (error) {
        ElMessage.error('请求题目内容时出错');
      }
    }
  }else{
    pId = route.query.id;
  }
  console.log("pid:"+pId)
});

// Watch for changes in content to validate JSON
watch(content, (newValue) => {
  if (type.value === '1') {
    try {
      JSON.parse(newValue); // Try to parse the content as JSON
    } catch (e) {
      ElMessage.error('无效的 JSON 格式');
      content.value = ''; // Clear content if invalid
    }
  }
});

// Before file upload check
function beforeUpload(file) {
  const isJSON = file.type === 'application/json';
  if (!isJSON) {
    ElMessage.error('上传文件只能是 JSON 类型!');
    return false;
  }
  return true;
}

// Handle file selection
function handleFileChange(file, newFileList) {
  fileList.value = [newFileList[newFileList.length - 1]];
}

// Submit data logic
async function submitData() {
  if (type.value === '3' && fileList.value.length === 0) {
    ElMessage.error('请先选择一个文件');
    return;
  }

  let url = `${API_BASE_URL}/ProblemsGroup/problems/uploadTestGroup`;
  let payload;

  // if(problemId.value==null){
  //   problemId.value= this.$store.getters.getProblemId;
  // }
  // console.log(store.getterszz.getProblemId)
  problemId.value= pId;
  console.log("pid:"+pId)
  if (type.value === '3') {
    const file = fileList.value[0];
    const formData = new FormData();
    formData.append('file', file.raw);
    formData.append('type', 'file');
    formData.append('problemId', problemId.value);
    payload = formData;
    await uploadFile(url, payload);
  } else {
    let label;
    if (type.value === '1') {
      label = 'json';
    } else if (type.value === '2') {
      label = 'url';
    }
    payload = {
      content: content.value,
      type: label,
      problemId: problemId.value
    };
    await uploadFile(url, payload);
  }
}

// File upload function
async function uploadFile(url, formData) {
  try {
    const response = await axios.post(url, formData, {
      headers: {
        'token': AUTH_TOKEN,
        'Content-Type': type.value === '3' ? 'multipart/form-data' : 'application/json'
      }
    });
    if (response.data.code === 200) {
      ElMessage.success('测试集上传成功!');
      if(editing==='1'){
        console.log("223232")
        await router.push({
          path: '/UploadCode',
          query: {
            editing: 1,
            problemId: pId,
            updateTestGroupId: response.data.data.testGroupId,
            updateTestGroupMongoId: response.data.data.id
          }
        });
        return;
      }
      console.log("1233333333333")
      console.log(problemId)
      console.log(response.data.data.testGroupId)
      console.log(response.data.data.id)
      await router.push({
        path: '/UploadCode',
        query: {
          problemId: pId,
          testGroupId: response.data.data.testGroupId,
          testGroupMongoId: response.data.data.id
        }
      });
    } else {
      ElMessage.error(`提交失败: ${response.data.msg}`);
    }
  } catch (error) {
    ElMessage.error('网络错误或服务器故障');
  }
}
</script>


<style scoped>
.next2 {
  margin-top: 20px;
  margin-bottom: 20px;
  float: right;
}

.main {
  display: flex;
  flex-direction: column;
  width: 60%;
  margin: 0 auto;
}

.upload-demo .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 5px;
  cursor: pointer;
  position: relative;
  padding: 15px 0;
}

.upload-demo i {
  color: #409EFF;
  font-size: 42px;
  vertical-align: middle;
}

.upload-demo .el-upload__text {
  display: block;
  font-size: 14px;
  color: #666;
}

.upload-demo .el-upload__tip {
  font-size: 12px;
  color: #999;
  line-height: 1.5;
  padding-top: 10px;
}
</style>
